import { useCallback } from 'react'
import { useChapterStore } from '@/store/chapterStore'
import { Chapter, CreateChapterParams } from '@/types/chapter'
import { useProjectStore } from '@/store/projectStore'

// 自定义钩子，简化章节状态的访问
export const useChapters = (projectId?: string) => {
  // 获取状态
  const {
    chapters,
    currentChapter,
    isLoading,
    error,
    fetchChapters,
    getChaptersByProject,
    createChapter,
    updateChapter,
    deleteChapter,
    selectChapter,
    reorderChapters
  } = useChapterStore()
  
  // 获取当前项目
  const { currentProject } = useProjectStore()
  
  // 当前项目的章节
  const projectChapters = useCallback(() => {
    const id = projectId || currentProject?.id
    if (!id) return []
    
    return getChaptersByProject(id)
  }, [projectId, currentProject, getChaptersByProject])
  
  // 获取当前项目的章节数量
  const chapterCount = useCallback(() => {
    return projectChapters().length
  }, [projectChapters])
  
  // 按状态过滤章节
  const getChaptersByStatus = useCallback((status: Chapter['status']) => {
    return projectChapters().filter(chapter => chapter.status === status)
  }, [projectChapters])
  
  // 创建章节并选择它
  const createAndSelectChapter = useCallback(async (params: CreateChapterParams) => {
    const newChapter = await createChapter(params)
    selectChapter(newChapter.id)
    return newChapter
  }, [createChapter, selectChapter])
  
  // 获取下一个章节
  const getNextChapter = useCallback((chapterId: string) => {
    const chapters = projectChapters()
    const index = chapters.findIndex(c => c.id === chapterId)
    
    if (index === -1 || index === chapters.length - 1) {
      return null
    }
    
    return chapters[index + 1]
  }, [projectChapters])
  
  // 获取上一个章节
  const getPreviousChapter = useCallback((chapterId: string) => {
    const chapters = projectChapters()
    const index = chapters.findIndex(c => c.id === chapterId)
    
    if (index <= 0) {
      return null
    }
    
    return chapters[index - 1]
  }, [projectChapters])
  
  // 获取章节的字数统计
  const getTotalWordCount = useCallback(() => {
    return projectChapters().reduce((total, chapter) => total + chapter.wordCount, 0)
  }, [projectChapters])
  
  return {
    // 状态
    chapters,
    currentChapter,
    isLoading,
    error,
    
    // 基础操作
    fetchChapters,
    getChaptersByProject,
    createChapter,
    updateChapter,
    deleteChapter,
    selectChapter,
    reorderChapters,
    
    // 高级操作
    projectChapters: projectChapters(),
    chapterCount: chapterCount(),
    getChaptersByStatus,
    createAndSelectChapter,
    getNextChapter,
    getPreviousChapter,
    getTotalWordCount: getTotalWordCount()
  }
} 